package com.example.rtmppusher.push;

import android.annotation.SuppressLint;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;

import com.example.rtmppusher.util.TaskQueue;


public class AudioRecordHandler {

    AudioRecord audioRecord;

    EventListener listener;

    final TaskQueue taskQueue = TaskQueue.get();

    int inputSamples;
    int inputBufferSize;

    int channels = 2;
    int sampleRate = 44100;
    int channelConfig = AudioFormat.CHANNEL_IN_STEREO;

    boolean recording = false;

    public AudioRecordHandler(EventListener eventListener) {
        this.listener = eventListener;
    }

    //设置音频编码信息
    public void setAudioEncodeInfo(int sampleRate, int channels, int inputSampleCount) {
        this.sampleRate = sampleRate;
        this.channels = channels;
        if (channels > 1)
            channelConfig = AudioFormat.CHANNEL_IN_STEREO;
        else
            channelConfig = AudioFormat.CHANNEL_IN_MONO;
        //设置每次输入的样本数
        inputSamples = inputSampleCount * 2; //每个样本16bit，2个字节
        int minBufferSize = AudioRecord.getMinBufferSize(44100, channelConfig, AudioFormat.ENCODING_PCM_16BIT);
        inputBufferSize = Math.max(minBufferSize, inputSamples);
    }

    //开始录音
    @SuppressLint("MissingPermission")
    public void start() {
        //创建录音器
        audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, 44100, channelConfig, AudioFormat.ENCODING_PCM_16BIT, inputBufferSize);
        //读取录音数据
        recording = true;
        taskQueue.add(() -> {
            while (recording) {
                byte[] bytes = new byte[inputSamples];
                int len = audioRecord.read(bytes, 0, bytes.length);
                if (len > 0)
                    listener.onAudioFrame(bytes);
            }
            audioRecord.stop();
            audioRecord.release();
            taskQueue.dispose();
        });
        audioRecord.startRecording();
    }

    //停止并释放录音器
    public void stop() {
        recording = false;
    }
}

